#include "recbox.h"
#include "ui_recbox.h"
#include <QJsonObject>
#include <QDebug>


RecBox::RecBox(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RecBox),
    row(1),
    col(4)
{
    ui->setupUi(this);

    //ui->itemListUpHLayout->addWidget(new RecBoxItem(this));
}

RecBox::~RecBox()
{
    delete ui;
}

void RecBox::initRecBoxUi(QJsonArray data, int row)
{
    if(row == 2)
    {
        this->row = row;
        col = 8;
    }
    else
    {
        ui->recListDown->hide();
    }

    imageList = data;

    count = imageList.size()/col;

    currentIndex = 0;

    createRecBoxItem();
}

void RecBox::createRecBoxItem()
{
    //删除旧元素
    QList<RecBoxItem*> oldUpList = ui->recListUp->findChildren<RecBoxItem*>();
    for(auto e : oldUpList)
    {
        ui->itemListUpHLayout->removeWidget(e);
        delete e;
    }

    QList<RecBoxItem*> oldDownList = ui->recListDown->findChildren<RecBoxItem*>();
    for(auto e : oldDownList)
    {
        ui->itemListDownHLayout->removeWidget(e);
        delete e;
    }

    int newIndex = currentIndex * col;

    for(int i = newIndex; i < newIndex + col; ++i)
    {
        RecBoxItem *item = new RecBoxItem();

        QJsonObject obj = imageList[i].toObject();
        item->setRecImage(obj.value("path").toString());
        item->setBoxItemText(obj.value("text").toString());

        if(i - newIndex < 4)
        {
            ui->itemListUpHLayout->addWidget(item);
        }
        else
        {
            ui->itemListDownHLayout->addWidget(item);
        }
    }
}

void RecBox::on_btUp_clicked()
{
    currentIndex--;
    if(currentIndex < 0)
    {
        currentIndex = count - 1;
    }

    createRecBoxItem();
}

void RecBox::on_btDown_clicked()
{
    currentIndex++;
    if(currentIndex >= count)
    {
        currentIndex = 0;
    }

    createRecBoxItem();
}
